from django.db import models
from django.contrib.auth.models import User


class Post(models.Model):
    """动态表 - 用户发布的绿色生活动态内容"""
    post_id = models.AutoField(primary_key=True, verbose_name='动态唯一ID', db_comment='动态唯一ID')
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        verbose_name='发布用户',
        db_comment='发布动态的用户',
        related_name='posts',
        null=True, blank=True
    )
    content = models.TextField(null=True, blank=True, verbose_name='动态的文本内容(可由AI生成)', db_comment='动态的文本内容(可由AI生成)')
    image_urls = models.JSONField(null=True, blank=True, verbose_name='存储图片URL的JSON数组', db_comment='存储图片URL的JSON数组')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发布时间', db_comment='发布时间')
    # 位置
    lat = models.FloatField(null=True, blank=True, verbose_name='纬度', db_comment='发布位置纬度')
    lng = models.FloatField(null=True, blank=True, verbose_name='经度', db_comment='发布位置经度')
    city = models.CharField(max_length=100, null=True, blank=True, verbose_name='城市', db_comment='发布所在城市')
    province = models.CharField(max_length=100, null=True, blank=True, verbose_name='省份', db_comment='发布所在省份')
    nation = models.CharField(max_length=100, null=True, blank=True, verbose_name='国家', db_comment='发布所在国家')
    
    tags = models.ManyToManyField('Tag', related_name='posts', blank=True)

    class Meta:
        db_table = 'xiangsu_posts'
        db_table_comment = '动态表-用户发布的绿色生活动态内容'
        verbose_name = '动态'
        verbose_name_plural = '动态'
        ordering = ['-created_at']

    def __str__(self):
        return f'动态{self.post_id}'
    
    def get_image_count(self):
        """获取图片数量"""
        if self.image_urls:
            return len(self.image_urls)
        return 0
    
    def add_image_url(self, image_url):
        """添加图片URL"""
        if not self.image_urls:
            self.image_urls = []
        
        if isinstance(self.image_urls, list):
            if image_url not in self.image_urls:
                self.image_urls.append(image_url)
        else:
            # 如果image_urls不是列表，转换为列表
            self.image_urls = [image_url]
        
        self.save()
    
    def remove_image_url(self, image_url):
        """移除图片URL"""
        if self.image_urls and isinstance(self.image_urls, list):
            if image_url in self.image_urls:
                self.image_urls.remove(image_url)
                self.save()
    
    def get_image_preview_html(self, max_images=3, thumbnail_size='50px'):
        """获取图片预览HTML"""
        if not self.image_urls:
            return '<div style="color: #999;">无图片</div>'
        
        from django.utils.html import format_html
        
        images_html = []
        for i, url in enumerate(self.image_urls[:max_images]):
            images_html.append(
                f'<img src="{url}" style="width: {thumbnail_size}; height: {thumbnail_size}; object-fit: cover; margin-right: 5px; border-radius: 3px;" alt="图片{i+1}">'
            )
        
        # 如果有更多图片，显示数量提示
        if len(self.image_urls) > max_images:
            images_html.append(f'<span style="margin-left: 5px; color: #666;">+{len(self.image_urls)-max_images}</span>')
        
        return format_html(''.join(images_html))
    
    def get_full_image_preview_html(self):
        """获取完整图片预览HTML"""
        if not self.image_urls:
            return '<div style="color: #999;">此动态没有图片</div>'
        
        from django.utils.html import format_html
        
        images_html = ['<div style="display: flex; flex-wrap: wrap; gap: 10px;">']
        for i, url in enumerate(self.image_urls):
            images_html.append(
                f'<div style="text-align: center;">'
                f'<img src="{url}" style="width: 120px; height: 120px; object-fit: cover; border-radius: 5px; border: 1px solid #ddd;" alt="图片{i+1}">'
                f'<div style="font-size: 12px; color: #666; margin-top: 5px;">图片{i+1}</div>'
                f'</div>'
            )
        
        images_html.append('</div>')
        return format_html(''.join(images_html))


class PostLike(models.Model):
    """动态点赞表 - 记录用户对动态的点赞行为"""
    like_id = models.AutoField(primary_key=True, verbose_name='点赞唯一ID', db_comment='点赞唯一ID')
    post = models.ForeignKey('Post', on_delete=models.CASCADE, db_column='post_id', verbose_name='被点赞的动态ID', db_comment='被点赞的动态ID')
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        verbose_name='点赞用户',
        db_comment='点赞的用户',
        related_name='post_likes',
        null=True, blank=True,  # 添加null和blank参数以支持现有数据
        db_column='user_ref_id'  # 修正为实际的数据库字段名
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='点赞时间', db_comment='点赞时间')

    class Meta:
        db_table = 'xiangsu_post_likes'
        db_table_comment = '动态点赞表-记录用户对动态的点赞行为'
        verbose_name = '动态点赞'
        verbose_name_plural = '动态点赞'
        unique_together = [['post', 'user']]

    def __str__(self):
        user_id = self.user.id if self.user else '未知用户'
        return f'用户{user_id}点赞动态{self.post.post_id}'


class Comment(models.Model):
    """评论表 - 动态的评论功能"""
    comment_id = models.AutoField(primary_key=True, verbose_name='评论唯一ID', db_comment='评论唯一ID')
    post = models.ForeignKey('Post', on_delete=models.CASCADE, db_column='post_id', verbose_name='被评论的动态ID', db_comment='被评论的动态ID')
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        verbose_name='评论用户',
        db_comment='发表评论的用户',
        related_name='comments',
        null=True, blank=True,  # 添加null和blank参数以支持现有数据
        db_column='user_id'  # 修正为实际的数据库字段名
    )
    content = models.TextField(verbose_name='评论内容', db_comment='评论内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='评论时间', db_comment='评论时间')

    class Meta:
        db_table = 'xiangsu_comments'
        db_table_comment = '评论表-动态的评论功能'
        verbose_name = '评论'
        verbose_name_plural = '评论'
        ordering = ['-created_at']

    def __str__(self):
        return f'评论{self.comment_id}'


class Tag(models.Model):
    tag_id = models.AutoField(primary_key=True, verbose_name='标签唯一ID', db_comment='标签唯一ID')
    name = models.CharField(max_length=50, unique=True, verbose_name='标签名称', db_comment='标签名称')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'xiangsu_tags'
        db_table_comment = '标签表'
        verbose_name = '标签'
        verbose_name_plural = '标签'
        ordering = ['name']

    def __str__(self):
        return self.name


# 已移除 EcoNews 模型，首页“环保动态”改为从社区动态聚合


class HomeBanner(models.Model):
    """首页轮播图配置（放在社区模块）"""
    ALIGN_CHOICES = [
        ('left', '靠左'),
        ('right', '靠右'),
        ('center', '居中'),
    ]

    banner_id = models.AutoField(primary_key=True, verbose_name='轮播唯一ID', db_comment='轮播唯一ID')
    image = models.ImageField(upload_to='home_banners/', null=True, blank=True, verbose_name='图片文件', db_comment='本地上传图片文件')
    image_url = models.CharField(max_length=500, null=True, blank=True, verbose_name='图片URL', db_comment='远程图片URL（可选）')
    title = models.CharField(max_length=100, null=True, blank=True, default='绿迹', verbose_name='标题', db_comment='标题')
    slogan = models.CharField(max_length=255, null=True, blank=True, default='让每一步都有环保温度', verbose_name='标语', db_comment='标语')
    align = models.CharField(max_length=10, choices=ALIGN_CHOICES, default='right', verbose_name='文案对齐', db_comment='文案对齐')
    is_active = models.BooleanField(default=True, verbose_name='是否展示', db_comment='是否展示在首页')
    order = models.IntegerField(default=0, verbose_name='排序', db_comment='越小越靠前')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', db_comment='创建时间')
    title_color = models.CharField(max_length=20, default='#ffffff', verbose_name='标题颜色', db_comment='标题颜色')
    slogan_color = models.CharField(max_length=20, default='#ffffff', verbose_name='标语颜色', db_comment='标语颜色')
    title_font_size = models.IntegerField(default=48, verbose_name='标题字号', db_comment='标题字号px')
    slogan_font_size = models.IntegerField(default=20, verbose_name='标语字号', db_comment='标语字号px')
    offset_x = models.IntegerField(default=0, verbose_name='水平偏移', db_comment='文本区域X偏移px')
    offset_y = models.IntegerField(default=0, verbose_name='垂直偏移', db_comment='文本区域Y偏移px')
    show_text = models.BooleanField(default=True, verbose_name='显示文案', db_comment='是否显示标题与标语')

    class Meta:
        db_table = 'xiangsu_home_banners'
        db_table_comment = '首页轮播图配置表'
        verbose_name = '首页轮播图'
        verbose_name_plural = '首页轮播图'
        ordering = ['order', '-created_at']

    def __str__(self):
        return self.title or f'轮播{self.banner_id}'
